from flask import Blueprint, jsonify, request
from flask_restful import reqparse

from src import db
from src.models.credit_cards_model import CreditCard

from .types.credit_card import CreditCardUpdateRequest

credit_bp = Blueprint("credit", __name__, url_prefix="/api/credit")


@credit_bp.route("/add", methods=["POST"])
def add_credit_card():
    """添加一条信用卡记录"""
    parser = reqparse.RequestParser()
    parser.add_argument("card_no", type=str, required=True, location="json")
    parser.add_argument("belong_bank", type=int, required=True, location="json")
    # parser.add_argument("files", type=list, required=False, location="json")
    # parser.add_argument("response_mode", type=str, choices=["blocking", "streaming"], location="json")
    # parser.add_argument("conversation_id", type=uuid_value, location="json")
    # parser.add_argument("parent_message_id", type=uuid_value, required=False, location="json")
    # parser.add_argument("retriever_from", type=str, required=False, default="web_app", location="json")

    args = parser.parse_args()

    try:
        CardsCls = CreditCard(**args)
        db.session.add(CardsCls)
        db.session.commit()
        print("插入成功，主键ID:", CardsCls.id)
        return (
            jsonify({"success": True, "message": "ok", "data": CardsCls.id}),
            200,
        )
    except Exception as e:
        print("add credit error", e)
        return jsonify({"success": False, "errMsg": str(e)}), 500


@credit_bp.route("/list", methods=["POST", "GET"])
def credit_list():
    page = request.args.get("page", 1, type=int)
    per_page = request.args.get("per_page", 10, type=int)
    pagination = (
        CreditCard.query.filter_by(status=1)
        .order_by(CreditCard.gmt_create.desc())
        .paginate(page=page, per_page=per_page, error_out=False)
    )
    dict_items: list[CreditCard] = pagination.items
    return jsonify(
        {
            "success": True,
            "data": [dict_item.to_dict() for dict_item in dict_items],
            "total": pagination.total,
            "page": page,
            "per_page": per_page,
        }
    )


@credit_bp.route("/update", methods=["POST"])
def update_credit_card():
    """修改一条信用卡记录"""
    # 使用 Pydantic 校验数据
    data = CreditCardUpdateRequest(**request.get_json())

    try:
        cardCls = CreditCard.query.get_or_404(data.id)
        if data.card_no:
            cardCls.card_no = data.card_no
        if data.belong_bank:
            cardCls.belong_bank = data.belong_bank
        db.session.commit()
        return jsonify({"success": True, "message": "ok", "data": True}), 200
    except Exception as e:
        print("update credit error", e)
        return jsonify({"success": False, "errMsg": str(e)}), 500
